/**
 * 
 */
package com.wbcs.system.function;

import java.lang.reflect.Method;
import java.util.Map;

import com.wbcs.system.function.ifexpression.AbsIfFunc;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.wbcs.config.Config;
import com.wbcs.util.Tools;
import sun.reflect.annotation.ExceptionProxy;

/**
 * 所有函数的解析辅助类并负责返回实际函数对象
 * @author hawkfly
 */
public class FuncAssistant {
	
	private static Log log=LogFactory.getLog(FuncAssistant.class);
	private final static FuncAssistant instance = new FuncAssistant();
	
	public static FuncAssistant getInstance()
	{
		return instance;
	}
	
	public boolean execFunc(IFuncDo ido)
	{
		FuncContextBean context = ido.getFuncContext(null);
		return context.getIfunc().exec(ido);
	}
	
	/**
	 * 根据函数类路径自动获取不同类型的函数对象
	 * @param funcClass
	 * @return
	 */
	public Object getRequireFunc(Class funcClass, String funcName,String[] arguments)
	{
		if(funcClass.getSuperclass() == AbsIfFunc.class)
		{
			if(arguments == null)
				return AbsIfFunc.createFunctionObj(funcClass, null, null, null, null);
			
			if(arguments.length != 4)
			{
				log.error("函数参数传递个数与定义不匹配");
				return null;
			}
			
			return AbsIfFunc.createFunctionObj(funcClass, funcName, arguments[0], arguments[1], arguments[2]);
		}
		
		return null;
	}
	
	public IFunc getHadParamsRequireFunc(String strFunc)
	{
		if(strFunc != null)
		{
			Map<String, IFunc> mFuncs = Config.getInstance().getmReportFunc();
		
			String funcName = Tools.getRgexMatchContent(strFunc, "[^()]+");
			if(!mFuncs.containsKey(funcName))
			{
				log.error("配置的函数名称在函数注册信息中不存在");
				return null;
			}
			
			String[] argments = Tools.getRgexMatchContent(strFunc, "(?<=\\().*(?=\\))").split(",");

			IFunc ifunc = mFuncs.get(funcName);
			if(ifunc == null)
			{
				log.error("函数对象初始化异常");
				return null;
			}
			
			return (IFunc)getRequireFunc(ifunc.getClass(), funcName, argments);
			
		}
		return null;
	}

	/**
	 * 根据strDo判断执行ido预设动作还是执行函数动作
	 * @param iFuncDo
	 * @param strDo
	 */
	public void execDoAction(IFuncDo iFuncDo, String strDo) throws Exception {
		String funcName = Tools.getRgexMatchContent(strDo, "[^()]+");
		IFunc ifunc = iFuncDo.getFuncContext(null).getIfunc();
		IFunc innerFunc = ifunc.getInnerFunc(funcName);
		if(innerFunc == null)
		{
			String doActionMethodName = "do" + Tools.firstCharUpperCase(strDo);
			Method[] methods = iFuncDo.getClass().getMethods();
			boolean isDoActionMethodName = false;
			for (Method method : methods)
			{
				if(method.getName().equals(doActionMethodName))
					isDoActionMethodName = true;
			}

			if(isDoActionMethodName)
			{//执行宿主实际实现动作
				Method doMethod = iFuncDo.getClass().getMethod(doActionMethodName);
				doMethod.invoke(iFuncDo);
			}
			else
			{//作为字符串常量对待
				iFuncDo.error(strDo);
			}
		}
		else
		{//执行内联函数
			innerFunc.exec(iFuncDo);
		}
	}

	public static void main(String[] args) {
		System.out.println(Tools.getRgexMatchContent("insert", "[^()]+"));
	}
}
